package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.pojo.Department;
import com.example.pojo.PageBean;
import com.example.pojo.Role;
import com.example.pojo.User;
import com.example.service.DepartmentService;
import com.example.service.RolePrivilegeService;
import com.example.service.RoleService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-08-20
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePrivilegeService rolePrivilegeService;

    /**
     * 登录
     * @return
     */
    @RequestMapping("/login.do")
    public String login(HttpServletRequest req,String loginName,String password) {
        //密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据loginName查询是否存在此用户
        User user = userService.login(loginName,password);

        //用户不存在
        if (user == null) {
            req.setAttribute("error","用户名或密码错误");
            return "/jsp/login.jsp";
        }

        //添加登陆用户到session中
        req.getSession().setAttribute("loginUser",user);
        return "redirect:/jsp/home/index.jsp";
    }

    /**
     * 退出登录
     * @param req
     * @return
     */
    @RequestMapping("/loginOut.do")
    public String loginOut(HttpServletRequest req) {
        //删除登录用户
        req.getSession().removeAttribute("loginUser");
        return "redirect:/jsp/login.jsp";
    }
    /**
     * 用户主页列表显示
     * @param model
     * @return
     */
    @RequestMapping("/list.do")
    public String getList(Model model,Integer currentPage,Integer pageSize) {
        if (currentPage==null) currentPage = 1;
        if (pageSize==null) pageSize = 5;
        // 分页
        PageBean<User> pageBean = userService.getPage(null, currentPage, pageSize);
        model.addAttribute("userList", pageBean.getRecordList());
        model.addAttribute("pageBean", pageBean);
        model.addAttribute("url", "/user/list.do?");

        return "/jsp/user/list.jsp";
    }

    /**
     * 进入添加用户界面
     * @param model
     * @return
     */
    @RequestMapping("/addUI.do")
    public String toAddUI(Model model) {
        //查询部门列表
        List<Department> deptList = departmentService.getDeptTree(null);
        model.addAttribute("deptList",deptList);
        //查询角色(岗位)列表
        List<Role> roleList = roleService.list();
        model.addAttribute("roleList",roleList);
        return "/jsp/user/add.jsp";
    }

    /**
     * 检查登录名是否存在
     * @param loginName
     * @return
     */
    @RequestMapping("/findByLoginName.do")
    @ResponseBody
    public String checkLoginName(String loginName) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(loginName != null, User::getLoginName, loginName);
        User user = userService.getOne(wrapper);
        if (user == null) {
            //用户不存在
            return "1";
        } else {
            //用户存在
            return "0";
        }
    }
    /**
     * 添加用户
     * @return
     */
    @RequestMapping("/add.do")
    public String addUser(Integer departmentId,String loginName,String name,String gender,
                          String phone,String email,String description,Integer[] rolesId) {
        //查询用户名是否重复
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(loginName != null, User::getLoginName,loginName);
        User one = userService.getOne(wrapper);
        if (one != null) {
            //用户存在,直接返回
            return "redirect:/user/list.do";
        }

        User user = new User(loginName,name,gender,phone,email,description,departmentId);
        //添加初始密码
        String encode = DigestUtils.md5DigestAsHex("123456".getBytes());
        user.setPassword(encode);

        boolean isAdd = userService.addUser(user,rolesId);

        return "redirect:/user/list.do";
    }

    /**
     * 初始化用户密码
     * @param uid
     * @return
     */
    @RequestMapping("/initPwd.do")
    public String initPwd(Integer uid) {
        //获取用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(uid != null, User::getUid, uid);
        User one = userService.getOne(wrapper);
        String encode = DigestUtils.md5DigestAsHex("123456".getBytes());
        one.setPassword(encode);

        //更新用户
        userService.updateById(one);

        return "redirect:/user/list.do";
    }

    /**
     * 删除用户
     * @param uid
     * @return
     */
    @RequestMapping("/delete.do")
    public String delete(Integer uid) {
        boolean delSuccess = userService.deleteByUid(uid);
        return "redirect:/user/list.do";
    }

    /**
     * 跳转修改页面
     * @param uid
     * @param model
     * @return
     */
    @RequestMapping("/editUI.do")
    public String editUser(Integer uid,Model model) {
        //获取用户信息
        List<User> users = userService.selectUserWithRoles(uid);
        User user = users.get(0);
        model.addAttribute("user", user);

        //查询部门列表
        List<Department> deptList = departmentService.getDeptTree(null);
        model.addAttribute("deptList",deptList);

        //查询角色(岗位)列表
        List<Role> roleList = roleService.list();
        model.addAttribute("roleList",roleList);

        return "/jsp/user/edit.jsp";
    }

    /**
     * 修改用户
     * @return
     */
    @RequestMapping("/edit.do")
    public String editUser(Integer uid,Integer departmentId,String loginName,String name,String gender,
                           String phone,String email,String description,Integer[] rolesId) {
        User user = new User(loginName,name,gender,phone,email,description,departmentId);
        user.setUid(uid);

        //更新用户和岗位关系表
        boolean success = userService.updateUserAndRole(user, rolesId);

        return "redirect:/user/list.do";
    }

    /**
     * 修改个人信息界面
     * @return
     */
    @RequestMapping("/editUserInfoUI.do")
    public String editUserInfoUI(HttpServletRequest req,Model model) {
        User loginUser = (User) req.getSession().getAttribute("loginUser");
        model.addAttribute("loginUser",loginUser);

        return "/jsp/user/editUserInfoUI.jsp";
    }

    /**
     * 修改用户头像
     * @return
     */
    @RequestMapping("/editUserInfo.do")
    public String editUserInfo(HttpServletRequest req){
        User user = (User) req.getSession().getAttribute("loginUser");
        String imgName = (String) req.getSession().getAttribute("imgName");
        user.setImage(imgName);
        //更新用户
        userService.updateById(user);

        //更新session中的信息
        req.getSession().setAttribute("loginUser", user);

        return "redirect:/jsp/home/right.jsp";
    }


    /**
     * 上传头像
     * @return
     */
    @RequestMapping("/uploadImg")
    @ResponseBody
    public String uploadImg(@RequestParam("file")MultipartFile file, HttpServletRequest request) {
        String basePath = request.getSession().getServletContext().getRealPath("/images");

        //file是临时文件，需要转存到指定位置，否则本次请求结束临时文件就会删除
        //原始文件名称
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID生成文件名，防止文件名重复造成文件覆盖
        String fileName = UUID.randomUUID().toString().replace("-","") + suffix;
//        System.out.println(fileName);
        //判断当前目录是否存在
        File dir = new File(basePath);
        if (!dir.isDirectory()) {
            //不存在，创建目录
            boolean mkdirs = dir.mkdirs();
        }

        try {
            //将文件转存到指定位置
            file.transferTo(new File(basePath , fileName));
//            System.out.println(basePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpSession session = request.getSession();
        session.setAttribute("imgName", fileName);

        return "../images/"+fileName;
    }

    /**
     * 删除旧头像
     */
    @RequestMapping("/deleteOldImg")
    @ResponseBody
    public void deleteOldImg(String img,HttpServletRequest req) {
        String imgName = img.substring(img.lastIndexOf("/")+1);
//        System.out.println(imgName);
        //本地图片存储路径
        String basePath = req.getSession().getServletContext().getRealPath("/images");
        //删除文件
        File file = new File(basePath + "/" + imgName);
        if (file.exists()) file.delete();

    }

    /**
     * 修改密码界面
     * @return
     */
    @RequestMapping("/editPasswordUI.do")
    public String editPasswordUI(HttpServletRequest req,Model model) {
        User loginUser = (User) req.getSession().getAttribute("loginUser");
        model.addAttribute("loginUser", loginUser);
        return "/jsp/user/editPasswordUI.jsp";
    }

    /**
     * 校验原始密码
     * @param password
     * @return
     */
    @RequestMapping("/checkPwd")
    @ResponseBody
    public String checkPwd(String password,HttpServletRequest req) {
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        System.out.println(password);

        User user = (User)req.getSession().getAttribute("loginUser");
        if (user.getPassword().equals(password)) {
            return "1";
        } else {
            return "0";
        }
    }
    /**
     * 修改密码
     * @param req
     * @param password
     * @return
     */
    @RequestMapping("/editPassword")
    public String editPassword(HttpServletRequest req,String password) {
        User user = (User)req.getSession().getAttribute("loginUser");
        //更改密码
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userService.updateById(user);
        //删除以登陆用户（重新登陆）
        req.getSession().removeAttribute("loginUser");

        return "redirect:/jsp/login.jsp";
    }
}

